/**
* @file  ComponentArea
* @author xiao_xie
* @date 2025-03-13
*/


import React, { useMemo } from 'react';
import useComponentStore, { ComponentNode } from '../../../store';
import useComponentConfigStore from '../../../store/componentConfig';
import HoverMask from '../../../components/Editor/HoverMask/HoverMask';
import ClickMask from '../../../components/Editor/ClickMask/ClickMask';
import WrapperCpmonent from '../../../components/Editor/Material/WrapperCpmonent';



const ComponentArea: React.FC = () => {

  const { components, setCurComponent, currentId } = useComponentStore();
  const { componentConfig } = useComponentConfigStore();
  const [hoverComponentId, setHoverComponentId] = React.useState<string | null>(null); // 选中的组件id

  // 鼠标移动事件，获取鼠标位置，判断是否在组件上，是的话，显示遮罩
  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    const path = e.nativeEvent.composedPath(); // 获取到当前鼠标位置的dom路径
    for (let i = 0; i < path.length; i += 1) {
      const ele = path[i] as HTMLElement;
      const componentId = ele.dataset?.componentId; // ele.dataset 获取dom元素的data属性
      if (componentId) {
        setHoverComponentId(componentId);
        return;
      }
    }
  }

  // 点击组件，设置选中组件
  const handleClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    const path = e.nativeEvent.composedPath(); // 获取到当前鼠标位置的dom路径
    for (let i = 0; i < path.length; i += 1) {
      const ele = path[i] as HTMLElement;
      const componentId = ele.dataset?.componentId; // ele.dataset 获取dom元素的data属性
      if (componentId) {
        setCurComponent(Number(componentId));
        return;
      }
    }
  }


  /**
   *  @description 渲染组件
   */
  const renderComponent = useMemo(() => {
    const recursionRender = (list: ComponentNode[]): React.ReactNode[] => {
      return list.map((component) => {
        const config = componentConfig[component.name];
        if (!config?.dev) {
          console.error(`组件 ${component.name} 未配置`);
          return null;
        }
        const element = React.createElement(
          config.dev,
          {
            key: component.id,
            id: component.id,
            name: component.name,
            ...config.defaultProps,
            ...component.props,
            // 递归渲染子组件（注意这里直接调用 recursionRender）
            children: component.children?.length 
              ? recursionRender(component.children) 
              : null
          }
        );
        return config.name !== 'Page' ? (
          <WrapperCpmonent
            key={component.id}
            id={component.id!}
            accept={config.allAccept}
            type={component.name}
            
          >
            {element}
          </WrapperCpmonent>
        ) : element;
      });
    };
  
    return recursionRender(components);
  }, [components, componentConfig]); // 确保 componentConfig 变化也会触发更新

  return <div
    className='bg-[#f1f1f1] p-5 h-full relative componentWrapper'
    onMouseMove={handleMouseMove}
    onMouseLeave={() => setHoverComponentId(null)}
    onClick={handleClick}
  >
    {
      renderComponent
    }

    {
      hoverComponentId && hoverComponentId !== currentId?.toString() && <HoverMask componentId={hoverComponentId} componentWrapper="componentWrapper" maskWrapper="maskWrapper" />
    }
    {
      currentId && <ClickMask componentId={currentId} componentWrapper="componentWrapper" maskWrapper="maskWrapper" />
    }

    <div className='maskWrapper'></div>
  </div>;
};
export default ComponentArea;
